"""
RAG模块初始化文件
自动安装必要的依赖包
"""

import subprocess
import sys
import importlib

def install_package(package_name):
    """安装Python包"""
    try:
        importlib.import_module(package_name)
        print(f"[OK] {package_name} 已安装")
    except ImportError:
        print(f"[INSTALL] 正在安装 {package_name}...")
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install", package_name])
            print(f"[OK] {package_name} 安装成功")
        except subprocess.CalledProcessError as e:
            print(f"[ERROR] {package_name} 安装失败: {e}")
            return False
    return True

def check_and_install_dependencies():
    """检查并安装所有必要的依赖包"""
    required_packages = [
        "elasticsearch",
        "elasticsearch-dsl", 
        "pymilvus",
        "pdfplumber",
        "Pillow",
        "dashscope"
    ]
    
    print("[CHECK] 检查RAG模块依赖包...")
    all_installed = True
    
    for package in required_packages:
        if not install_package(package):
            all_installed = False
    
    if all_installed:
        print("[SUCCESS] 所有依赖包检查完成！")
    else:
        print("[WARNING] 部分依赖包安装失败，请手动安装")
    
    return all_installed

# 自动检查依赖
if __name__ == "__main__":
    check_and_install_dependencies()
else:
    # 当模块被导入时自动检查依赖
    check_and_install_dependencies()
